package com.aqielife.netty.simple.handler;

import com.alibaba.fastjson2.JSON;
import com.aqielife.netty.simple.Response;
import com.aqielife.netty.simple.command.Command;
import com.aqielife.netty.simple.enums.CommandType;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

/**
 * 处理操作请求
 * 1. 连接
 * 2. 私聊
 * 2. 群聊
 */
@Slf4j
public class WebsocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame frame) throws Exception {
        try{
            Command command = JSON.parseObject(frame.text(), Command.class);
            switch (CommandType.match(command.getCode())) {
                case CONNECTION -> ConnectionHandler.execute(ctx, command);
                case CHAT -> ChatHandler.execute(ctx, frame);
                case JOIN_GROUP -> JoinGroupHandler.execute(ctx);
                default -> ctx.channel().writeAndFlush(Response.ok("unsupported code"));
            }

        }catch (Exception e) {
            log.error(e.getMessage());
            ctx.channel().writeAndFlush(Response.ok(e.getMessage()));
        }
    }
}
